let disp = require("../../../../utils/broadcast");
var app = getApp()
const recorderManager = wx.getRecorderManager();


Page({
  data: {
    role: 0,
    isgq: false,
    recordState: false, //录音状态
    content: '', //内容
    upload_picture_list: [],
    typedate: 0,
    username: {
      your: "",
    },
    shouwtab: false,
    show: !0,
    hide: !1,
    xing: 0,
    evaluate: true,
    figure: 0, // 0 患者     1 医生
    dex: "", //1 处方  ！1不是
    imgs: [],
    suc: "",
    list: [],
    play_show: true, //播放
    thtime: '00:00', //录音时长
    txt_show: true,
    page: 0,
  },
  // 转文字
  bindzhuan(e) {
    var that = this
    var id = e.currentTarget.dataset.id
    var index = e.currentTarget.dataset.index
    var list = that.data.list
    list[index].txt_show = false
    app.util.request({
      'url': 'entry/wxapp/follow.shibie',
      data: {
        id: id
      },
      success: function (res) {
        list[index].context = res.data.result[0]
        that.setData({
          list: list
        })
      }
    })

  },
  /*** 提示*/
  tip: function (msg) {
    wx.showModal({
      title: '提示',
      content: msg,
      showCancel: false
    })
  },
  handleRecordStart: function (e) {
    console.log("开始录音", e)
    this.setData({
      is_clock: true, //长按时应设置为true，为可发送状态
      startPoint: e.touches[0], //记录触摸点的坐标信息
    })
    //设置录音参数
    const options = {
      duration: 10000,
      sampleRate: 16000,
      numberOfChannels: 1,
      encodeBitRate: 48000,
      format: 'mp3'
    }
    recorderManager.start(options); //开始录音
    wx.showToast({
      title: '录音中',
      icon: 'none',
    })
  },
  handleRecordStop: function (e) {
    console.log(app)
    var that = this;
    var uniacid = app.siteInfo.uniacid
    recorderManager.stop() //结束录音
    //此时先判断是否需要发送录音
    if (this.data.is_clock == true) {
      //对停止录音进行监控
      var that = this
      recorderManager.onStop((res) => {
        console.log(res)
        this.setData({
          src: res.tempFilePath
        })
        var time = res.duration
        //对录音时长进行判断，少于2s的不进行发送，并做出提示
        if (res.duration < 2000) {
          wx.showToast({
            title: '录音时间太短，请长按录音',
            icon: 'none',
            duration: 1000
          })
        } else {
          var m, s;
          m = Math.floor(time / 1000 / 60 % 60);
          s = Math.floor(time / 1000 % 60);
          if (m < 10) {
            m = '0' + m
          }
          if (s < 10) {
            s = '0' + s
          }
          this.setData({
            thtime: m + ':' + s,
            endtime: time
          })
          // that.tip("录音完成！")
          //进行语音发送
          const {
            tempFilePath
          } = res;
          //上传录制的音频

          wx.uploadFile({
            url: this.data.url + 'app/index.php?i=' + uniacid + '&c=entry&a=wxapp&do=Uploadvideo&m=hyb_yl',
            filePath: tempFilePath,
            name: 'upfile',
            success: function (res) {
              var mp3 = res.data
              var openid = that.data.openid
              var zid = that.data.zid
              app.util.request({
                'url': 'entry/wxapp/follow.add_chat',
                data: {
                  mp3: mp3,
                  thtime: that.data.endtime,
                  val: '语音',
                  zid: zid,
                  openid: that.data.openid,
                  role: that.data.role
                },
                success: function (res) {
                  //console.log(res)
                  that.setData({
                    page: 0,
                    list: [],
                    shouwtab: false,
                    upload_picture_list: []
                  })
                  that.getOrderlist()

                }
              })
            }
          })
        }
      })
    }
  },

  /*** 播放录音*/
  playRecord: function (e) {
    var that = this;
    var src = e.currentTarget.dataset.src
    var thtime = e.currentTarget.dataset.thtime
    var index = e.currentTarget.dataset.index
    var list = that.data.list
    if (src == '' || src == undefined) {
      that.tip("请先录音！")
      return;
    } else {
      that.innerAudioContext.src = e.currentTarget.dataset.src;
      that.innerAudioContext.play()

      list[index].play_show = false
      that.setData({
        list: list
      })
    }
    setInterval(function () {
      list[index].play_show = true
      that.setData({
        list: list
      })
      clearInterval()
    }, thtime)
  },
  //图片预览
  lookimg(e) {
    let url = e.currentTarget.dataset.img
    let lists = e.currentTarget.dataset.url
    var index = e.currentTarget.dataset.index
    let that = this;
    let src = e.currentTarget.dataset.img;
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: [src] // =============重点重点=============
    })
  },
  //关闭追问
  closezhuiwen() {
    this.setData({
      shouwtab: false
    })
  },
  //提交追问
  submitformzw(e) {
    var that = this;
    var val = e.detail.value.zhuiwen;
    var upload_picture_list = that.data.upload_picture_list
    var zid = that.data.zid
    var typedate = that.data.typedate
    var arr = {
      'text': val,
      'typedate': typedate,
      'upload_picture_list': upload_picture_list,
    }
    app.util.request({
      'url': 'entry/wxapp/follow.add_chat',
      data: {
        arr: arr,
        val: val,
        zid: zid,
        openid: that.data.openid,
        role: that.data.role
      },
      success: function (res) {
        //console.log(res)
        that.setData({
          page: 0,
          list: [],
        })
        wx.showToast({
          title: '发送成功',
        })
        that.getOrderlist()
        that.setData({
          shouwtab: false,
          upload_picture_list: []
        })
      }
    })
  },
  //图片上传
  uploadimg: function () {
    let that = this;
    var uniacid = app.siteInfo.uniacid
    var data_arr = that.data.upload_picture_list;
    wx.chooseImage({
      count: 5,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths
        for (var i = 0; i < tempFilePaths.length; i++) {
          wx.uploadFile({
            url: that.data.url + 'app/index.php?i=' + uniacid + '&c=entry&a=wxapp&do=Uploadback&m=hyb_yl',
            filePath: tempFilePaths[i],
            name: 'upfile',
            formData: [],
            success: function (res) {
              //console.log(res)
              data_arr.push(res.data)
              that.setData({
                upload_picture_list: data_arr,
                typedate: 1
              })
            }
          })
        }
      }
    })
  },
  // 删除图片
  clearImg: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.ind;
    //console.log(index);
    var nowList = []; //新数据
    var imglis = that.data.upload_picture_list; //原数据
    imglis.splice(index, 1);
    that.setData({
      upload_picture_list: imglis
    })
  },
  // 图片预览
  previewImage: function (e) {
    var current = e.target.dataset.src
    wx.previewImage({
      current: current,
      urls: this.data.upload_picture_list
    })
  },
  // 关闭评价
  closeevaluate() {
    this.setData({
      evaluate: false
    })
  },
  // 发布提问
  submitform(e) {
    let vals = e.detail.value.liuyan;
  },
  // options = 系统传入的 url 参数
  onLoad(options) {
    clearInterval(this.time)
    var that = this
    wx.showLoading()
    var zid = options.zid
    app.util.request({
      'url': 'entry/wxapp/hzbingli.url',
      success: function (res) {
        console.log(res)
        that.setData({
          url: res.data,
        })
      }
    })
    wx.setNavigationBarTitle({
      title: options.title,
    })
    var openid = options.openid
    that.setData({
      zid: zid,
      openid: openid,
      role: options.role
    })

    that.getusefw()
    that.getOrderlist()
    that.innerAudioContext = wx.createInnerAudioContext();
  },
  onShow: function (e) {
  },
  onHide: function () {
    clearInterval(this.time)
    var that = this
    var docindex = that.data.docindex
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];
    that.setData({
      docindex: docindex
    })
  },
  onUnload() {
    disp.fire("em.chatroom.leave");
    clearInterval(this.time)
    var docindex = this.data.docindex
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];
    prevPage.setData({
      docindex: docindex
    })
  },
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading();
    // 停止下拉动作
    wx.hideNavigationBarLoading();
    wx.stopPullDownRefresh();
    this.getOrderlist();
  },
  //查询患者服务包
  getusefw() {
    var that = this
    app.util.request({
      'url': "entry/wxapp/follow.user_fuwu_data",
      data: {
        openid: that.data.openid,
        zid: that.data.zid
      },
      success: function (res) {
        that.setData({
          isgq: res.data.isgq
        })
      }
    })
  },
  getOrderlist() {
    var that = this
    var zid = that.data.zid
    var openid = that.data.openid
    that.time = setInterval(function () {
      app.util.request({
        'url': 'entry/wxapp/follow.chat_list',
        data: {
          openid: openid,
          zid: zid,
        },
        success: function (res) {
          var list = res.data
          for (var i = 0; i < list.length; i++) {
            var m, s;
            m = Math.floor(list[i].thtime / 1000 / 60 % 60);
            s = Math.floor(list[i].thtime / 1000 % 60);
            if (m < 10) {
              m = '0' + m
            }
            if (s < 10) {
              s = '0' + s
            }
            list[i].endtime = m + ':' + s
            list[i].play_show = true
            list[i].txt_show = true
            list[i].context = ''
          }
          var list1 = [];
          for (var i = 1; i <= list.length; i++) {
            list1.push(list[list.length - i]);
          }
          
          that.setData({
            list: list1
          })
          wx.hideLoading({
            success: (res) => {},
          })

        }
      })
    }, 1000)
  },
  onReachBottom: function () {

  },
  clickshow: function (t) {
    this.setData({
      show: !0,
      hide: !1
    });
  },
  clickshow1: function (t) {
    this.setData({
      show: !1,
      hide: !0
    });
  },
  tabinput2(e) {
    var that = this
    that.setData({
      shouwtab: !this.data.shouwtab
    })
  },
  previewImg: function (t) {
    //console.log(t)
    var current = t.target.dataset.src;
    //预览图片
    var imgs = []
    imgs.push(current)
    wx.previewImage({
      current: current,
      urls: imgs,
    });
  },

});